#include "thread.h"
#include <QtGui>

temp::temp(QPlainTextEdit *t,QTcpSocket *c)
{
	text = t;
	client = c;
}

void temp::Doit()
{
	QByteArray ba=client->readAll();
	QString str = QString::fromLocal8Bit(ba.constData(),ba.size());

	text->appendPlainText(str);
	client->close();

	delete this;
}







thread::thread(QWidget *parent, Qt::WFlags flags)
	: QMainWindow(parent, flags)
{
	//ui.setupUi(this);
	QFrame * frame = new QFrame;
	QVBoxLayout * vbl = new QVBoxLayout;
//	 lab = new QLabel("What the fk");

	text = new QPlainTextEdit;
	vbl->addWidget(text);
	frame->setLayout(vbl);
	this->setCentralWidget(frame);;

	server = new QTcpServer;
	connect(server, SIGNAL(newConnection()), this, SLOT(NewCon()));
	server->listen(QHostAddress::Any,2222);
}

thread::~thread()
{

}

void thread::NewCon()
{
	QTcpSocket *clientConnection = server->nextPendingConnection();
	connect(clientConnection, SIGNAL(disconnected()),
		clientConnection, SLOT(deleteLater()));
	//! [7] //! [8]
	//QByteArray ba=clientConnection->readAll();
	//QString str = QString::fromLocal8Bit(ba.constData(),ba.size());
	//lab->setText(str);
	temp * tt = new temp(text,clientConnection);
	connect(clientConnection,SIGNAL(readyRead()),tt,SLOT(Doit()));

	clientConnection->write("HTTP/1.1 200 OK\r\nContent-Length: 41\r\n\r\n<html><body><h1>whatthefk</h1></body></html>");
	//clientConnection->disconnectFromHost();
	//clientConnection->close();
}

FortuneServer::FortuneServer(QObject *parent)
	: QTcpServer(parent)
{
}
//! [0]

//! [1]
void FortuneServer::incomingConnection(int socketDescriptor)
{
	QString fortune("HTTP/1.1 200 OK\r\n\r\n<html><body><h1>whatthefk</h1></body></html>");
	FortuneThread *thread = new FortuneThread(socketDescriptor, fortune, this);
	connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
	thread->start();
}
//! [1]

FortuneThread::FortuneThread(int socketDescriptor, const QString &fortune, QObject *parent)
	: QThread(parent), socketDescriptor(socketDescriptor), text(fortune)
{
}
//! [0]

//! [1]
void FortuneThread::run()
{
	QTcpSocket tcpSocket;
	//! [1] //! [2]
	if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
		emit error(tcpSocket.error());
		return;
	}
	//! [2] //! [3]

	QByteArray block;
	QDataStream out(&block, QIODevice::WriteOnly);
	out.setVersion(QDataStream::Qt_4_0);
	//out << (quint16)0;
	//out << text;
	//out.device()->seek(0);
	//out << (quint16)(block.size() - sizeof(quint16));
	//! [3] //! [4]
	//out<<"HTTP/1.1 200\r\n\r\n<html><body><h1>whatthefk</h1></body></html>";
	tcpSocket.write("HTTP/1.1 200 OK\r\nContent-Length: 41\r\n\r\n<html><body><h1>whatthefk</h1></body></html>");
	tcpSocket.disconnectFromHost();
	tcpSocket.waitForDisconnected();
}
